package com.jhg.drgclinicalpathway.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jhg.drgclinicalpathway.dao.*;
import com.jhg.drgclinicalpathway.domain.*;
import com.jhg.drgclinicalpathway.service.FormWordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.events.EndDocument;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 病人信息
 */
@RestController
@RequestMapping("patient")
@Slf4j(topic = "PatientController")
public class PatientController {


    @Autowired
    PatientDao patientDao;

    @GetMapping("ls")
    public RpnMsg list(@RequestParam("stime") String stime,
                       @RequestParam("etime") String etime,
                       @RequestParam(defaultValue = "") String c,
                       @RequestParam(value = "s", defaultValue = "") String s,
                       @RequestParam(value = "st", defaultValue = "") String st,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "size", defaultValue = "10") Integer size,
                       @RequestParam(value = "order", defaultValue = "出院日期") String order,
                       @RequestParam(defaultValue = "") String deptValue,
                       @RequestParam(defaultValue = "") String doctorValue,
                       @RequestParam(defaultValue = "入院日期") String t,
                       @RequestParam(defaultValue = "") String warns,
                       @RequestParam(defaultValue = "") String 病组编码,
                       @RequestParam(defaultValue = "") String 路径名称,
                       @RequestParam(value = "desc", defaultValue = "desc") String desc,
                       @RequestParam(defaultValue = "false") String needwarn
    ) {

        QueryWrapper<PatientInfo> queryWrapper = new QueryWrapper<PatientInfo>();
        if (!t.equals("在院")) {
            queryWrapper.between(t, stime + " 00:00:00", etime + " 23:59:59");
        } else {
            queryWrapper.eq(t, 1);
        }
        if (!StringUtils.isEmpty(warns)) {
            queryWrapper.exists("SELECT 1 FROM dbo.LJ_病人评估预警 b WHERE VDCP_病人信息_路径指标参考.病人ID = b.病人标识 AND b.预警ID IN (" + warns + ")");
        }
        if (!StringUtils.isEmpty(st)) {
            if ("是否评估".equals(st)) {
                queryWrapper.eq(st, 1);
            } else if ("未入组".equals(st)) {
                queryWrapper.and(w -> w.in("病组编码", "0000", "0000组", "未入组").or().like("病组编码", "%QY%"));
            }
        }
        if (!StringUtils.isEmpty(deptValue)) {
            queryWrapper.eq("科室", deptValue);
        }
        if (!StringUtils.isEmpty(doctorValue)) {
            queryWrapper.eq("医生", doctorValue);
        }
        if (!StringUtils.isEmpty(病组编码)) {
            queryWrapper.eq("病组编码", 病组编码);
        }
        if (!StringUtils.isEmpty(路径名称)) {
            queryWrapper.eq("路径名称", 路径名称);
        }
        if (!StringUtils.isEmpty(s) && StringUtils.isEmpty(c)) {
            queryWrapper.and(w -> w.like("病组编码", s)
                    .or().like("病组名称", "s")
                    .or().like("主要诊断编码", s)
                    .or().like("主要诊断名称", s)
                    .or().like("主要手术名称", s)
                    .or().like("主要手术编码", s)
                    .or().like("病人姓名", s)
                    .or().eq("住院号", s));
        } else if (!StringUtils.isEmpty(c) && !StringUtils.isEmpty(s)) {
            queryWrapper.and(w -> w.like(c, s));
        }

        if (desc.equals("asc")) {
            queryWrapper.orderByAsc(t);
        } else {
            queryWrapper.orderByDesc(t);
        }
        Page<PatientInfo> pg = new Page<PatientInfo>(page, size);

        IPage<PatientInfo> patientInfoIPage = patientDao.selectPage(pg, queryWrapper);
        if(needwarn.equals("true")){
            List<String> 版本s = patientInfoIPage.getRecords().stream()
                    .filter(it->!StringUtils.isEmpty(it.get版本ID()))
                    .map(it -> it.get版本ID()).collect(Collectors.toList());

            List<PathTpl> pathTpls = tplDao.selectBatchIds(版本s);
            for (PatientInfo record : patientInfoIPage.getRecords()) {
                String id = record.getId();
                Optional<PathTpl> first = pathTpls.stream().filter(it -> it.getId().equals(record.get版本ID())).findFirst();
                if(first.isPresent()){
                    record.set版本名称(first.get().get路径版本());
                    record.set模板名称(first.get().get名称());
                }
                List<Map<String, Object>> maps = 临床路径模板Dao.PRO_LJ_病人路径预警_EXEC(id);
                record.setWarms(maps);
            }
        }


//        if(patientInfoIPage.getRecords()!=null){
//            List<String> codes = patientInfoIPage.getRecords().stream()
//                    .filter(it->!StringUtils.isEmpty(it.getDrgcode()))
//                    .map(it -> it.getDrgcode()).collect(Collectors.toList());
//            if(codes.size()>0){
//                List<Map<String, Object>> stdLs = tplDao.病组标植值ByCode(codes);
//                for (PatientInfo record : patientInfoIPage.getRecords()) {
//                    if(StringUtils.isEmpty(record.getDrgcode())) continue;
//
//                    Optional<Map<String, Object>> 分组编码 = stdLs.stream().filter(it -> {
//                        String drgCode = it.get("分组编码").toString();
//                        return record.getDrgcode().equals(drgCode);
//                    }).findFirst();
//                    if(分组编码.isPresent()){
//                        record.setStd(分组编码.get());
//                    }
//                }
//            }
//        }


        return RpnMsg.SUCCESS(patientInfoIPage);
    }

    @Autowired
    PathTplDao tplDao;

    @GetMapping("patientinfo")
    public RpnMsg patientinfo(String id) {
        PatientInfo patientInfo = patientDao.selectById(id);
        String drgcode = patientInfo.getDrgcode();
        String pattern = ".[A-J].*";
        //JSONObject o= JSON.parseObject(JSON.toJSONString(patientInfo));
        if (!StringUtils.isEmpty(drgcode) && !StringUtils.isEmpty(patientInfo.getOptcode())) {
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(drgcode);
            //是手术病人
            if (m.matches()) {
                Date oPtDate = patientDao.getOPtDate(id, patientInfo.getOptcode());
                patientInfo.setOptDate(oPtDate);
            }
        }
        return RpnMsg.SUCCESS(patientInfo);
    }


    @Autowired
    CommonDao commonDao;

    @GetMapping("cost")
    public RpnMsg cost(String pid) {
        List<Map<String, Object>> cost = commonDao.cost(pid);
        return RpnMsg.SUCCESS(cost);
    }

    @GetMapping("dec")
    public RpnMsg dec(String pid) {
        List<Map<String, Object>> cost = commonDao.dec(pid);
        return RpnMsg.SUCCESS(cost);
    }

    @GetMapping("opt")
    public RpnMsg opt(String pid) {
        List<Map<String, Object>> cost = commonDao.opt(pid);
        return RpnMsg.SUCCESS(cost);
    }


    @Autowired
    Pro2CostDao pro2CostDao;

    /**
     * 根据病人查找相关项目信息
     *
     * @param id
     * @return
     */
    @GetMapping("getProTypeByPatId")
    public RpnMsg getProTypeByPatId(String id) {
        List<Map<String, Object>> proTypeByPatId = pro2CostDao.findProTypeByPatId(id);
        return RpnMsg.SUCCESS(proTypeByPatId);
    }

    @GetMapping("findProTypeAndNameByPatId")
    public RpnMsg findProTypeAndNameByPatId(String id) {

        PatientInfo patientInfo = patientDao.selectById(id);

        List<Map<String, Object>> proTypeByPatId = pro2CostDao.findProTypeAndNameByPatId(id);
        //路径当中的药品
        //List<Map<String, Object>> 药品Ls = commonDao.selectByDis("药品", "", patientInfo.getDiscode(), "");
//        药品Ls.stream().filter((m)->{
//            String name = m.get("名称").toString();
//            String proType=m.get("类型A").toString();
//
//        });
        //只取临床路径当中有的
//        proTypeByPatId=proTypeByPatId.stream().filter((m)->{
//            if(m.containsKey("name")&&m.get("name")!=null){
//                String name=m.get("name").toString();
//                String proSubType=m.get("proSubType").toString();
//                return 药品Ls.stream().filter((mm)->{
//                    String 名称=mm.get("名称").toString();
//                    String 说明=mm.get("说明").toString();
//
//                    return name.equals(名称)&&proSubType.equals(说明);
//                }).count()>0;
//            }
//            return true;
//        }).collect(Collectors.toList());

        return RpnMsg.SUCCESS(proTypeByPatId);
    }

    @GetMapping("proc4cost")
    public RpnMsg proc4cost() {
        List<Map<String, Object>> maps = pro2CostDao.proc2cost();
        return RpnMsg.SUCCESS(maps);
    }

    /**
     * 病人基础项目
     *
     * @param id
     * @return
     */
    @GetMapping("pat-basiccostById")
    public RpnMsg patBasicCostById(String id) {
        List<Map<String, Object>> maps = pro2CostDao.patBasicCostById(id);
        return RpnMsg.SUCCESS(maps);
    }

    /**
     * 获取评价结果
     *
     * @param id
     * @param l
     * @return
     */
    @GetMapping("pat-result")
    public RpnMsg patResult(@RequestParam(value = "id") String id,
                            @RequestParam(value = "l", defaultValue = "0") Integer l) {
        List<Map<String, Object>> maps = patientDao.PRO_LJ_病人路径评估_EXEC(id, l);
        return RpnMsg.SUCCESS(maps);
    }

    @GetMapping("pat-day-info")
    public RpnMsg patDayInfo(String id, String pid, String t) {
        List<Map<String, Object>> 病人天数信息 = patientDao.LJ_病人路径评估_从表_EXEC(id, pid, t);
        return RpnMsg.SUCCESS(病人天数信息);
    }

    @PostMapping("project-out-scope")
    public RpnMsg projectOutScope(@RequestParam("id") String id, @RequestParam("ls") List<String> ls) {

        List<Map<String, Object>> 超范围项目 = patientDao.超范围项目(id, ls);

        return RpnMsg.SUCCESS(超范围项目);
    }

    @GetMapping("sync")
    public RpnMsg sync(String id) {

        try {
            patientDao.PRO_LJ_路径自动处理_AUTO(id);
        } catch (Exception ex) {
            String msg = ex.getMessage();
            if (ex.getCause() != null) {
                msg = ex.getCause().getMessage();
            }
            return RpnMsg.FAIL(msg);
        }


        return RpnMsg.SUCCESS();
    }


    @GetMapping("zdjl")
    public RpnMsg zdjl(String id) {
        List<Map<String, Object>> 诊断信息 = patientDao.诊断信息(id);
        return RpnMsg.SUCCESS(诊断信息);
    }

    @GetMapping("sljl")
    public RpnMsg sljl(String id) {
        List<Map<String, Object>> 手术信息 = patientDao.手术信息(id);
        return RpnMsg.SUCCESS(手术信息);
    }

    /**
     * 病人费用信息
     *
     * @param id
     * @return
     */
    @GetMapping("cost-summary")
    public RpnMsg costSummary(String id) {
        List<Map<String, Object>> list = pro2CostDao.costSummary(id);
        return RpnMsg.SUCCESS(list);
    }

    /**
     * 科室列表
     *
     * @return
     */
    @GetMapping("dept")
    @Cacheable(cacheNames = "allDepts", key = "#t")
    public RpnMsg dept(@RequestParam(defaultValue = "00") String t) {
        System.out.println("没有 缓存");
        List<String> 科室 = patientDao.科室();
        return RpnMsg.SUCCESS(科室);
    }

    /**
     * 科室列表
     *
     * @return
     */
    @GetMapping("dept2doc")
    @Cacheable(cacheNames = "dept2doc", key = "#t")
    public RpnMsg dept2doc(@RequestParam(defaultValue = "00") String t) {
        List<Map<String, Object>> 科室医生 = patientDao.科室医生();
        return RpnMsg.SUCCESS(科室医生);
    }


    /**
     * 科室列表
     *
     * @return
     */
    @GetMapping("doctor")
    @Cacheable(cacheNames = "allDoctor", key = "#t")
    public RpnMsg doctor(@RequestParam(defaultValue = "00") String t) {

        List<String> 医生 = patientDao.医生();
        return RpnMsg.SUCCESS(医生);
    }

    @Autowired
    FormWordService formWordService;


    @PostMapping("form-word")
    public void lineWayReport(String id, HttpServletResponse rep) throws Exception {

        formWordService.gender(id, rep);
    }

    @GetMapping("check-way")
    public RpnMsg checkWay(String id) throws Exception {

        PatientInfo info = formWordService.处理路径ID(id);

        if (StringUtils.isEmpty(info.get路径ID())) {
            return RpnMsg.FAIL("没有找到路径信息");
        }
        return RpnMsg.SUCCESS();
    }

    @Autowired
    临床路径模板Dao 临床路径模板Dao;

    @GetMapping("warning")
    public RpnMsg warning(String id) {
        List<Map<String, Object>> maps = 临床路径模板Dao.PRO_LJ_病人路径预警_EXEC(id);
        return RpnMsg.SUCCESS(maps);
    }

    /**
     * 通过病人ID获取诊断与路径的关联关系
     *
     * @param id
     * @return
     */
    @GetMapping("zd2path")
    public RpnMsg zd2path(String id) {
        List<Map<String, Object>> maps = 临床路径模板Dao.诊断2路径(id);
        return RpnMsg.SUCCESS(maps);
    }

    @GetMapping("proljzxqk")
    public RpnMsg proljzxqk(String pid, String id) {
        List<Map<String, Object>> maps = 临床路径模板Dao.PRO_LJ_路径执行情况(pid, id);
        return RpnMsg.SUCCESS(maps);
    }

    @GetMapping("drg-waring")
    public RpnMsg drgWaring(@RequestParam(defaultValue = "出院日期") String t,
                            @RequestParam(defaultValue = "") String stime,
                            @RequestParam(defaultValue = "") String etime,
                            @RequestParam(defaultValue = "科室") String grp,
                            @RequestParam(defaultValue = "") String ks,
                            @RequestParam(defaultValue = "总人次 desc") String order,
                            @RequestParam(defaultValue = "") String rz,
                            @RequestParam(defaultValue = "") String rj,
                            @RequestParam(defaultValue = "100") String size
    ) {
        String wh = "1=1";
        if (!StringUtils.isEmpty(rz)) {
            wh += " and 是否入组=1";
        }
        if (!StringUtils.isEmpty(ks)) {
            wh += " and 科室='" + ks + "'";
        }
        if (!StringUtils.isEmpty(rj)) {
            wh += " AND 是否入径=1";
        }
        stime += " 00:00:00";
        etime += " 23:59:59";

        List<Map<String, Object>> 支付风险分析 = 临床路径模板Dao.支付风险分析(t, stime, etime, grp, order, size, wh);
        return RpnMsg.SUCCESS(支付风险分析);
    }

    @GetMapping("pre-warn-msg")
    public RpnMsg preWarnMsg() {
        List<Map<String, Object>> 预警信息 = 临床路径模板Dao.预警信息();
        return RpnMsg.SUCCESS(预警信息);
    }

    @GetMapping("drgkssearch")
    public RpnMsg drgkssearch(String stime, String etime
            , @RequestParam(defaultValue = "分组编码") String grp
            , @RequestParam(defaultValue = "10") Integer size,
                              @RequestParam(defaultValue = "人次") String order
    ) {
        stime = stime + " 00:00:00";
        etime += " 23:59:59";
        List<Map<String, Object>> maps = 临床路径模板Dao.DRG亏损查询(stime, etime, grp, size, order);
        return RpnMsg.SUCCESS(maps);
    }

    @GetMapping("zdjb")
    public RpnMsg 重点疾病分析(String stime, String etime,
                               @RequestParam(defaultValue = "") String t,
                               @RequestParam(defaultValue = "10") Integer size,
                               @RequestParam(defaultValue = "人次") String order,
                               @RequestParam(defaultValue = "b.路径名称,b.分组编码,a.路径ID") String grp,
                               @RequestParam(defaultValue = "") String s,
                               @RequestParam(defaultValue = "") String w
    ) {
        stime = stime + " 00:00:00";
        etime += " 23:59:59";
        List<Map<String, Object>> maps = 临床路径模板Dao.重点疾病分析(stime, etime, size, order, t, s,grp,w);
        return RpnMsg.SUCCESS(maps);
    }

    @GetMapping("zdjbbar")
    public RpnMsg zdjbbar(String stime, String etime,
                          @RequestParam(defaultValue = "") String t,
                          @RequestParam(defaultValue = "") String c,
                          @RequestParam(defaultValue = "") String lp
    ) {
        List<Map<String, Object>> 重点疾病图表分析 = 临床路径模板Dao.重点疾病图表分析(stime, etime, lp, t, c);
        return RpnMsg.SUCCESS(重点疾病图表分析);
    }


    @GetMapping("yufxpg")
    public RpnMsg 有盈余风险的病例评估(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "出院日期") String t,
            @RequestParam(defaultValue = "") String stime,
            @RequestParam(defaultValue = "") String etime,
            @RequestParam(defaultValue = "") String deptValue,
            @RequestParam(defaultValue = "1") Integer ykf,
            @RequestParam(defaultValue = "") String wids,
            @RequestParam(defaultValue = "") String warns

            //deptValue
    ){
        Page<Map<String,Object>> p=new Page<>(page,size);
        Page<Map<String, Object>> pa = patientDao.有盈余风险的病例评估ByPage(p,t,stime,etime,deptValue,ykf,wids,warns);
        return RpnMsg.SUCCESS(pa);
    }


}
